# -*- coding:utf-8 -*-
import os,sys
import re
import traceback
import time
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
import supeanut_config
from CommonLib.mylog import mylog
from CommonLib.StockTool import StockTool
from CommonLib.FileTool.CsvTool import CsvTool
from DataAPI.SinaAPI import SinaAPI


'''
作者：supeanut
创建时间：2016-xx-xx xx:xx:xx
功能描述：
	xxx
	xxxxx
相关配置：
	supeanut_config.XXX
历史改动：
	2016-xx-xx: xxxxxx
'''
class SinaMinDataSupport:
	# init what
	def __init__(self):
		#self.param = supeanut_config.PARAM
		self.stocktool = StockTool()
		self.sina_api = SinaAPI()
		self.bulk_num = supeanut_config.SINA_API_BULKNUM
		self.field = supeanut_config.SINA_MINDATA_FIELD
		self.csvindex = supeanut_config.SINA_MINDATA_INDEX
		self.store_base_path = supeanut_config.SINA_MINDATA_CSV_PATH
		self.csv_tool = CsvTool()

	# mode='stock' or 'index'
	# 返回的代码前缀分为：sz、sh、in
	def get_data(self, mode='stock'):
		# 获取全市场股票代码，包括上市和停牌
		flag, stock_code_L = self.stocktool.get_all_stock_code('L')
		if flag is False:
			return False, stock_code_L
		flag, stock_code_S = self.stocktool.get_all_stock_code('S')
		if flag is False:
			return False, stock_code_S
		flag, stock_code_UN = self.stocktool.get_all_stock_code('UN')
		if flag is False:
			return False, stock_code_UN
		stock_code = stock_code_L + stock_code_S + stock_code_UN
		# 获取重要指数代码
		index_code = self.stocktool.get_import_index_code()
		if mode == 'index':
			stock_code = index_code
		# 分批次访问sina api
		bulk_max = int(len(stock_code)/self.bulk_num)
		# --需要尾部处理
		bulk_tail = False
		if bulk_max * self.bulk_num <> len(stock_code):
			bulk_max += 1
			bulk_tail = True
		# 全市场所有数据，或index所有数据
		all_data = {}
		for bulk_index in range(0, bulk_max):
			if bulk_index == bulk_max - 1 and bulk_tail == True:
				stock_code_bulk = stock_code[bulk_index*self.bulk_num: len(stock_code)]
			else:
				stock_code_bulk = stock_code[bulk_index*self.bulk_num: (1+bulk_index)*self.bulk_num]
			flag, data = self.sina_api.cur_hq(mode, stock_code_bulk)
			if flag is False:
				return False, data
			for code in data:
				code_info = data[code]
				if mode == 'index':
					# index的前缀为in，区别于个股
					code = 'in' + code[2:]
				all_data[code] = code_info
		return True, all_data

	# 保存到本地csv文件
	# date参数用于指定保存的文件夹
	def store_data(self, data, date):
		store_path = os.path.join(self.store_base_path, date)
		for code in data:
			code_info = data[code]
			onerecord_list = [code]
			for field in self.field[1:]:
				onerecord_list.append(code_info[field])
			# 可选append，或者update方式
			flag, msg = self.csv_tool.append_csvfile([onerecord_list], store_path, code)
			#flag, msg = self.csv_tool.update_csvfile(self.csvindex, [onerecord_list], store_path, code)
		if flag is False:
			return False, msg
		return True, 'suc'


if __name__ == '__main__':
	obj = SinaMinDataSupport()
	flag, msg = obj.get_data(mode = 'stock')
	#print flag, msg
	print len(msg)
	print obj.store_data(msg, date='2016-12-11')
